package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.Deposito;
import ar.republicagroup.gestion.services.DepositoServices;
import ar.republicagroup.gestion.services.ExportarServices;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.TableColumnAdjuster;
import ar.republicagroup.gestion.util.helpers.Formato;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;

/**
 *
 * @author DIEGOALV
 */
public class modalPanelAddLiquidacionDeposito extends javax.swing.JDialog {

    /* Services */
    DepositoServices    depositoServices      = (DepositoServices)SpringUtils.getBean("depositoServices");
    ExportarServices exportarServices         = (ExportarServices)SpringUtils.getBean("exportarServices");
    
    private static Logger log                 = Logger.getLogger(modalPanelAddLiquidacionDeposito.class);
    private List<Deposito> depositoList;
    
    double totalMontoDepositos;
    private Task task;
    
    public modalPanelAddLiquidacionDeposito(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    
    public void cargarTablaDeposito(List<Deposito> depositoList){
        try{
            DefaultTableModel model = (DefaultTableModel) tblDepositos.getModel();
            model.getDataVector().clear();
            tblDepositos.clearSelection();
            
            for(Deposito deposito : depositoList){
               model.addRow(new Object[]{ deposito,Formato.fechaDDMMYY(deposito.getFechaDeposito()),deposito.getClienteId().getNombre(),deposito.getComision().doubleValue(),Formato.decimalComaMilesConSigno(deposito.getEfectivoDepositado().doubleValue()),deposito.getCuentaBancoId().getNombre()});
               totalMontoDepositos += deposito.getEfectivoDepositado().doubleValue();
            }
        
            TableColumnAdjuster tca = new TableColumnAdjuster(tblDepositos);
            tca.adjustColumns();
            tblDepositos.setModel(model);
            tblDepositos.repaint();
        }catch(Exception ex){
           log.error(ex.getMessage(),ex);
        }
    }
    
    public void mostrarBarraDeProgresoEIniciarTask(){
            final BarraDeProgreso barra;
            barra = new BarraDeProgreso(this, false);
            barra.setLocationRelativeTo(this);
            barra.setVisible(true);
            task = new Task();
            task.addPropertyChangeListener(new PropertyChangeListener() {

             @Override
             public void propertyChange(PropertyChangeEvent pcEvt) {
                if (SwingWorker.StateValue.DONE == pcEvt.getNewValue()) {
                   Toolkit.getDefaultToolkit().beep(); 
                   barra.setVisible(false);
                   barra.dispose();            
                }
             }
          });
       
            task.execute();
    }
    
    
         
    class Task extends SwingWorker<Void, Void> {
        
        @Override
        public Void doInBackground() throws Exception {
            liquidar();
            return null;
        }
      
    }
  
    public List<Deposito> getDepositoList() {
        return depositoList;
    }

   
    public void setDepositoList(List<Deposito> depositoList) {
        this.depositoList = depositoList;
    }
    
    
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        lblCliente = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblDepositos = new javax.swing.JTable();
        btnLiquidacion = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblDepositoTotal = new javax.swing.JLabel();
        lblTotal = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("...: Depósitos en efectivo :...");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Confirme depósito"));

        jLabel1.setText("Liquidación cliente:");

        lblCliente.setText("nombre_cliente");

        tblDepositos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Fecha depósito", "Cliente", "Comisión efectivo", "Efectivo depositado", "Cuenta"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblDepositos.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane1.setViewportView(tblDepositos);

        btnLiquidacion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/check.png"))); // NOI18N
        btnLiquidacion.setText("Es correcto, liquidar!");
        btnLiquidacion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLiquidacionActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setText("Depósitos a liquidar:");

        jLabel3.setText("Total:");

        lblDepositoTotal.setText("jLabel4");

        lblTotal.setText("jLabel5");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblDepositoTotal)
                    .addComponent(lblTotal))
                .addContainerGap(235, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(lblDepositoTotal))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lblTotal))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 404, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(lblCliente))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(52, 52, 52)
                        .addComponent(btnLiquidacion)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnCancelar, btnLiquidacion});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(lblCliente))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLiquidacion)
                    .addComponent(btnCancelar))
                .addGap(0, 16, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        List<Deposito> depositos = getDepositoList();
        lblCliente.setText(depositos.get(0).getClienteId().getNombre());
        cargarTablaDeposito(depositoList);
        lblDepositoTotal.setText(String.valueOf(depositoList.size()));
        lblTotal.setText(Formato.decimalComaMilesConSigno(totalMontoDepositos));
       
    }//GEN-LAST:event_formWindowOpened

    private void btnLiquidacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLiquidacionActionPerformed
        int respuestaConfirma = JOptionPane.showConfirmDialog(this,"¿Confirma la liquidación?" , UIMessages.getQuestionMessage("defaultQuestionTitle"), JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
        if(respuestaConfirma == JOptionPane.OK_OPTION){
            mostrarBarraDeProgresoEIniciarTask();
        }
    }//GEN-LAST:event_btnLiquidacionActionPerformed

    
    
    
    public void liquidar(){
        
        boolean errorAlReportar = false;
        
        for(Deposito deposito : depositoList){
            deposito.setFechaLiquidacion(new Date());
            depositoServices.update(deposito);
        }
        
         depositoServices.setComisionDeposito(depositoList.get(0).getClienteId().getComisionDeposito().doubleValue());
         depositoServices.setTotalMontoDepositos(totalMontoDepositos);
        
         Map parametros = new HashMap();
         parametros.put("fecha", Formato.cambiarFechaAFormatoLocal(new Date()));
         parametros.put("cliente",depositoList.get(0).getClienteId().getNombre());
         parametros.put("total_monto_depo",Formato.decimalComaMiles(totalMontoDepositos));
         parametros.put("com_deposito",depositoList.get(0).getClienteId().getComisionDeposito());
         parametros.put("subtotal_depo",Formato.decimalComaMilesConSigno(depositoServices.getSubtotalLiquidacion()));
         parametros.put("subtotal_gestion",Formato.decimalComaMilesConSigno(depositoServices.getSubtotalLiquidacion()));
         parametros.put("notas","");
         
         try{
                exportarServices.reporteDeDepositosToPDF(null, parametros);  
                
            }catch(Exception ex){
                log.info("Error al generar reporte "+ex.getMessage(), ex);
                errorAlReportar = true;
            }
         
         
         if(!errorAlReportar){
            JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("onCompleteExport"), UIMessages.getInfoMessage("onCompleteExport_title"), JOptionPane.INFORMATION_MESSAGE);
            dispose();
         }else{
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("onExportError"), UIMessages.getErrorMessage("defaultErrorTitle"),JOptionPane.ERROR_MESSAGE); 
         }
         
         
         
    }
    
    
    
    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed


    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(modalPanelAddLiquidacionDeposito.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(modalPanelAddLiquidacionDeposito.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(modalPanelAddLiquidacionDeposito.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(modalPanelAddLiquidacionDeposito.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                modalPanelAddLiquidacionDeposito dialog = new modalPanelAddLiquidacionDeposito(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnLiquidacion;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCliente;
    private javax.swing.JLabel lblDepositoTotal;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JTable tblDepositos;
    // End of variables declaration//GEN-END:variables

    
}
